/*
 * @Author: wuzhen
 * @Date: 2020-01-13 13:28:41
 * @LastEditors  : wuzhen
 * @LastEditTime : 2020-01-14 15:03:40
 * @Description: 头部注释
 */
import Vue from "vue";
import VueRouter from "vue-router";
import store from "@/store";

Vue.use(VueRouter);

const routes = [
  {
    path: "/",
    name: "login",
    component: () => import("@/views/login")
  },
  {
    path: "*",
    name: "dashboard",
    component: () => import("@/views/dashboard"),
    redirect: { name: "chat" },
    children: [
      {
        path: "/chat",
        name: "chat",
        component: () => import("@/views/chat")
      },
      {
        path: "/addressBook",
        name: "addressBook",
        component: () => import("@/views/addressBook")
      }
    ]
  }
];

const router = new VueRouter({
  mode: "history",
  base: process.env.BASE_URL,
  routes
});

router.beforeEach((to, from, next) => {
  if (store.state.chat.jsessionId) {
    // 根据token判断用户是否处于登录状态
    if (to.path === "/") {
      next({
        path: "/chat",
        replace: true
      });
    } else if (to.path.indexOf("/404") >= 0 || to.path.indexOf("/401") >= 0) {
      // 防止因重定向到error页面造成beforeEach死循环
      next();
    } else {
      next();
    }
  } else {
    next();
  }
});

export default router;